package cn.weekimwee.firstlineofcodeforkotlin.unit10

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.view.View
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_service.*
import org.jetbrains.anko.startService
import org.jetbrains.anko.stopService

class ServiceActivity : BaseActivity() {

    private var download:MyService.DownloadBinder?=null

    private val connection = object :ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            service?.let {
                download = it as MyService.DownloadBinder
                download?.startDownload()
                download?.getProgress()
            }
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_service)
        start.setOnClickListener { it.onClick() }
        stop.setOnClickListener { it.onClick() }
        bind.setOnClickListener { it.onClick() }
        unbind.setOnClickListener { it.onClick() }
    }

    private fun View.onClick() {
        when (this.id) {
            R.id.start -> {
                startService<MyService>()
            }
            R.id.stop -> {
                stopService<MyService>()
            }
            R.id.bind -> {
                bindService(Intent(this@ServiceActivity,MyService::class.java),connection, Context.BIND_AUTO_CREATE)
            }
            R.id.unbind -> {
                unbindService(connection)
            }
        }
    }
}
